package hrc.wow_notifier;

import hrc.wow_notifier.service.NotifyService;
import hrc.wow_notifier.service.NotifyServiceFactory;

import java.util.Calendar;
import java.util.Date;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class AlarmReceiver extends BroadcastReceiver {

	private boolean askStatus(String serverName, int mode, Intent intent) {
		NotifyService notifyService = NotifyServiceFactory
				.createNotifyService(mode);
		boolean newStatus = notifyService.isServerOnline(serverName);
		intent.putExtra("online", newStatus);
		return newStatus;
	}

	private void notify(Context context, Intent intent) {
	
		intent.putExtra("shoke", true);
		intent.setClass(context, WOWNotifier.class);
		context.startActivity(intent);

	}

	@Override
	public void onReceive(Context context, Intent intent) {
		// get data
		String serverName = intent.getStringExtra("serverName");
		int mode = intent.getIntExtra("mode", 0);
		boolean oldStatus = intent.getBooleanExtra("online", false);
		
		Calendar c = Calendar.getInstance();
		Date date = new Date();
		c.setTime(date);
		int dateOfWeek = c.get(Calendar.DAY_OF_WEEK);
		
		//这样写是为了减少流量
		//星期二每隔指定时间(一小时)，都会向服务器发出请求，如果旧状态为离线而当前为在线，则发出通知
		//而除了星期二的其他时间，只会在旧状态是离线的情况下才询问服务器
		// on tuesday
		if(dateOfWeek==3){
			boolean newStatus=askStatus(serverName, mode, intent);
			if(!oldStatus&&newStatus){
				notify(context, intent);
			}
			
		}else{
			//如果旧状态是离线，而且新状态是在线
			if(!oldStatus&&askStatus(serverName, mode, intent)){
				notify(context, intent);
			}
		}
	}
}
